package com.adkun.community.controller;

import com.adkun.community.dao.elasticsearch.DiscussPostRepository;
import com.adkun.community.entity.DiscussPost;
import com.adkun.community.entity.Page;
import com.adkun.community.entity.User;
import com.adkun.community.service.DiscussPostService;
import com.adkun.community.service.LikeService;
import com.adkun.community.service.UserService;
import com.adkun.community.util.CommunityUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.adkun.community.util.CommunityConstants.ENTITY_TYPE_POST;

@Controller
// Controller访问路径可以省略
public class HomeController {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private DiscussPostRepository postRepository;

    @GetMapping("/")
    public String root() {
        return "forward:/index";
    }

    /**
     * 管理员用
     * 将之前的帖子（热帖）刷入Elasticsearch
     * @return
     */
    @GetMapping("/esintosql")
    @ResponseBody
    public String esIntoSql() {
        postRepository.saveAll(discussPostService.findDiscussPosts(0, 0, 10000, 1));
        return CommunityUtil.getJSONString(0);
    }

    /**
     * 首页
     *
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(path = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page, @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        //支持分页
        // 可以把page装到Model里，但可以省略，因为Spring MVC DispacherServlet会自动把Page实例化并装入Model
        // 所以，在thymeleaf可以直接访问Page对象中的数据。
        page.setRows(discussPostService.findDiscussPostsCount(0));
        // 分页以后将orderMode保持在地址（GET）
        page.setPath("/index?orderMode=" + orderMode);

        List<DiscussPost> list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                // 把返回的讨论区帖子以及对应userId的User信息存到一个List里
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                User user = userService.findUserById(post.getUserId());
                map.put("user", user);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);

            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("orderMode", orderMode);
        return "/index";
    }

    @RequestMapping(path = "/error", method = RequestMethod.GET)
    public String getErrorPage() {
        return "/error/500";
    }

    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }
}
